/*************************************************************************
	> File Name: IdeaDao.java
	> Author: 
	> Mail: 
	> Created Time: 2016年10月11日 星期二 20时54分53秒
 ************************************************************************/


package peter.webtools.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import peter.webtools.beans.Idea;

@Repository
public class IdeaDao extends BaseDao {
    private static final Logger log = LoggerFactory.getLogger(IdeaDao.class);
    private static IdeaDao dao = null;
    @Resource
    private JdbcTemplate jdbcTemplate;
    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    public boolean addIdea(String content, String tags) {
        String sql = tags == null ?
            "insert into ideas(content) values('" + content + "')" :
            "insert into ideas(content, tags) values('" + content + "', '" + tags + "')";
        jdbcTemplate.execute(sql);
        return true;
    }

    public List<Idea> getIdeas() {
        return getIdeas(0, 10);
    }

    public List<Idea> getIdeas(int offset, int number) {
        List<Idea> list = new ArrayList<Idea>();
        String sql = "select * from ideas order by time desc limit " + number + " offset " + offset;

        jdbcTemplate.query(sql, new RowCallbackHandler() {
            public void processRow(ResultSet rs) throws SQLException {
                Idea idea = new Idea();
                idea.setId(rs.getInt("id"));
                idea.setContent(rs.getString("content"));
                idea.setTime(rs.getTimestamp("time"));
                idea.setTags(rs.getString("tags"));
                list.add(idea);
            }
        });
        
        return list;
    }

    /**
     * 根据id获取任务。
     */
    public Idea getIdea(int id) {
        String sql = "select * from ideas where id = " + id;
        List<Idea> list = new ArrayList<Idea>();

        jdbcTemplate.query(sql, new RowCallbackHandler() {
            public void processRow(ResultSet rs) throws SQLException {
                Idea idea = new Idea();
                idea.setId(rs.getInt("id"));
                idea.setContent(rs.getString("content"));
                idea.setTime(rs.getTimestamp("time"));
                idea.setTags(rs.getString("tags"));
                list.add(idea);
            }
        });

        return list.size() > 0 ? list.get(0) : null;
    }
}
